<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/24
 * Time: 10:32
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\wap\controller\Kbxcoupon;
use think\Db;
use think\Request;
use think\Loader;
use think\Cookie;
use think\Session;
use app\common\extend\Random;
use think\Validate;
class Member1 extends Api
{
    protected $model = null;
    protected $uid = null;
    protected $member_type_id = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        header('Access-Control-Allow-Origin:*');
        $uid=request()->post('openid');
        $member= db('member')->where('program_openid',$uid)->find();

        if(empty($member)){
            $this->error('请点"更新资料"登陆','',-1);
        }
        $this->uid = $member['member_id'];
        $this->member_type_id = $member['member_type_id'];
        $this->model = model('Member')->get($this->uid);
    }




    /**
     * 修改会员等级
     * @param $level_id
     */
    public function memberLevel($level_id){
        $result = $this->model->save(['member_type_id'=>$level_id]);
        if($result){
            $this->success('修改成功','',0);
        }else{
            $this->error('修改失败','',-1);
        }
    }


    /**
     * 积分日志表
     */
    public function integralLog(){
        $data = db('member_integrallog')->where(array('member_id'=>$this->uid))->order('create_time desc')->select();
        $kk=[];
        foreach ($data as $v){
            $v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
            $kk[]=$v;
        }

        $this->success('',$kk,0);
    }



    /**
     * 个人中心数据获取
     * @ is_apply 判断是否申请会员 0 等于未申请 1=已申请
     */
    public function center(){
        $d=db('coupondetails')
            ->alias('a')
            ->where('a.member_id', $this->model->member_id)
            ->join('coupon d','a.coupon_id=d.coupon_id')
            ->where('a.usestatus',0)
            ->field('d.*,a.id,a.starttime')
            ->select();
        $discoun_per=db('member_type')->where('member_type_id',  $this->member_type_id)->where('type_status',1)->field('member_type_id,type_name')->find();
        $jishu=0;
        foreach ($d as $v){
            if ($v['end_usetime'] < time()) {

            } else {
                $jishu++;
            }
        }
        $data['member_id'] = $this->model->member_id;
        $data['member_nickname'] = $this->model->member_nickname;
        $data['member_phone'] = $this->model->member_phone;
        $data['member_integral'] = $this->model->member_integral;
        $data['member_money'] = $this->model->member_money;
        $data['is_apply']= $this->model->is_apply;
        $data['is_admin']= $this->model->is_admin;
        $data['member_coupon'] =$jishu;
        $data['member_type'] =$discoun_per;
        $this->success('',$data,0);
    }


    /**
     * 我的订单
     * @param string $status    订单状态:1=待付款,2=已付款待使用,3=已使用待评价,4=已评价,5=退款中,6=已取消
     */
    public function order1(){
        $status= input('status');
        $status= !empty($status)?$status:'';
        $where['member_id'] = $this->uid;
        if($status!=''){
            $where['order_status'] = $status;
        }
        $data = db('order')->where($where)->where('isdelete',0)->where('order_ascription',1)->order('creattime','desc')->select();
        foreach ($data as $k=>$v){
            $goods_name=db('goods')->where('goods_id',$v['goods_id'])->field('goods_name')->find();
            if (empty($v['orderperson'])){
                $person=db('orderperson')->where('order_id',$v['order_id'])->field('person_name,person_num')->select();
            }else{
                $person=json_decode($v['orderperson'],true);
                unset($v['orderperson']);
            }

            $data[$k]['goods_name']=$goods_name['goods_name'];
            if (!empty($v['creattime'])){
                $data[$k]['creattime']=date('Y-m-d H:i:s',$v['creattime']);
            }
            if (!empty($v['updatetime'])){
                $data[$k]['updatetime']=date('Y-m-d H:i:s',$v['updatetime']);
            }
            if ($person==true){
                $data[$k]['person']=$person;
            }else{
                $this->error('当前没有订单','',0);
            }
        }
        $this->success('',$data,0);
    }


    public function order(){
        $status= input('status');
        $member_id= $this->uid;
        $status= !empty($status)?$status:'';
        $where['member_id'] = $member_id;
        $data=[];
        if($status!=''){
            $where['order_status'] = $status;
        }
        $data2 = db('order')->where($where)->where('isdelete',0)->order('creattime','desc')->select();
        foreach ($data2 as $k=>$v){
            $goods_name=db('goods')->where('goods_id',$v['goods_id'])->field('goods_name')->find();
            if (empty($v['orderperson'])){
                $person=db('orderperson')->where('order_id',$v['order_id'])->field('person_name,person_num')->select();
            }else{
                $person=json_decode($v['orderperson'],true);
                unset($v['orderperson']);
            }
            $v['goods_name']=$goods_name['goods_name'];
            if (!empty($v['creattime'])){
                $v['creattime']=date('Y-m-d H:i:s',$v['creattime']);
            }
            if (!empty($v['updatetime'])){
                $v['updatetime']=date('Y-m-d H:i:s',$v['updatetime']);
            }
            if ($person==true){
                $v['person']=$person;
            }else{
                return json_encode(['msg'=>'当前没有订单','code'=>0,'data'=>'']);
            }
            $data[]=$v;
        }
        return json_encode(['msg'=>'','code'=>0,'data'=>$data]);
    }


    public function orderevaluate(){
        $order_id= input('order_id');
        $where['member_id']=  $this->uid;
        $data = db('order')->where('order_id',$order_id)->where('isdelete',0)->find();
        $goods_name=db('goods')->where('goods_id',$data['goods_id'])->field('goods_name')->find();
        if (empty($data['orderperson'])){
            $person=db('orderperson')->where('order_id',$data['order_id'])->field('person_name,person_num')->select();
        }else{
            $person=json_decode($data['orderperson'],true);
            unset($data['orderperson']);
        }

        if (!empty($person)){
            $data['person']=$person;
        }else{
            return json_encode(['msg'=>'当前没有订单','code'=>0,'data'=>'']);

        }


        $data['goods_name']=$goods_name['goods_name'];
        if (!empty($data['creattime'])){
            $data['creattime']=date('Y-m-d H:i:s',$data['creattime']);
        }
        if (!empty($data['updatetime'])){
            $data['updatetime']=date('Y-m-d H:i:s',$data['updatetime']);
        }
        return json_encode(['msg'=>'ok','code'=>0,'data'=>$data]);
    }




    /**
     * 未付款取消订单
     * @param $order_id
     */
    public function removeOrder($order_id){
        $order_id= input('order_id');
        $order = model('Order')->where(['isdelete'=>0])->get($order_id);
        if($order['order_status']==1){
            $result = $order->delete();
            if ($order['coupon_type']=='KBX'){
                if (!empty($order['cost_ticket_id'])){
                    $Kbxcoupon=  new Kbxcoupon();
                    $d= $Kbxcoupon->refundCashCoupon($order['member_id'],$order['cost_ticket_id'],$order['order_no']);
                    if (empty($d)){
                        $d=true;

                    }else{
                        $d=json_decode($d,true);
                        if (!empty($d['msg'])) return json_encode(['msg'=>$d['msg'],'code'=>101]);
                    }
                    if ($d!=true){
                        return json_encode(['msg'=>'删除失败','code'=>101,'data'=>'1']);
                    }
                }
            }else{
                db('coupondetails')->where('id',$order['cost_ticket_id'])->update(['usestatus'=>0]);
            }
            return json_encode(['msg'=>'取消成功','code'=>0,'data'=>'']);
        }else{
            return json_encode(['msg'=>'只有未付款订单才能取消','code'=>101,'data'=>'']);
        }
    }




    /**
     * 订单完成或终止删除
     * @param $order_id
     */
    public function delorder(){
        $order_id=input('order_id');
        $data['order_id'] = $order_id;
        $data['isdelete'] = 1;
        $dat=db('order')->where('order_id',$order_id)->find();
        if ($dat['coupon_type']=='KBX' && $dat['order_status']<3){
            if (!empty($dat['cost_ticket_id'])){
                $Kbxcoupon = new Kbxcoupon();
                $d = $Kbxcoupon->refundCashCoupon($dat['member_id'], $dat['cost_ticket_id'], $dat['order_no']);
                if (empty($d)) {
                    $d = db('order')->where('order_id',$order_id)->update([
                        'isdelete'=>1,
                    ]);
                    $d = true;
                } else {
                    $d = json_decode($d, true);
                    if (!empty($d['msg'])) return json_encode(['msg' => $d['msg'], 'code' => 101]);
                }

                if ($d != true) {
                    return json_encode(['msg' => '删除失败', 'code' => 101, 'data' => '1']);
                }
            }
        }else{
            db('coupondetails')->where('id',$dat['cost_ticket_id'])->update(['usestatus'=>0]);
            $d = db('order')->where('order_id',$order_id)->update([
                'isdelete'=>1,
            ]);
            if ($d != true) {
                return json_encode(['msg' => '删除失败', 'code' => 101, 'data' => '1']);
            }
        }

        if ($d == true) {
            return json_encode(['msg'=>'删除成功','code'=>0,'data'=>'']);
        }
    }



    /**
     * 评论显示
     * @param $order_id
     */
    public function evaluate($order_id){
        $order = model('order')->where(['isdelete'=>0])->get($order_id);
        $goods = model('Goods')->get($order->goods_id);
        $data['cost_money'] = $order['cost_money'];
        $data['adult_num'] = $order['adult_num'];
        $data['starttime'] = date('Y-m-d H:i',$goods['starttime']);
        $data['order_id'] = $order['order_id'];
        $this->success('',$data,0);
    }



    /**
     * 新增订单评论
     * @param $content  评论内容
     * @param string $comment_img   评论图片
     * @param $integral     获取积分
     */
    public function evaluateAdd($content,$comment_img='',$integral){
        $post=request()->post();
        $data=[];
        if ( !empty($post)){
            $comment= db('comment')->where([ 'member_id'=>$this->uid, 'goods_id'=>$post['goods_id']])->find();
            $creattime= $comment['creattime']+30;
            if (time()<$creattime){
                $shu=[
                    'code'=>101,
                    'msg'=>'30秒内不能重复提交评论',
                ];
                return json_encode($shu);
            }

            Db::startTrans();
            try{
                $result = db('comment')->insert([
                    'content'=>$post['content'],
                    'comment_img'=>$post['content_img'],
                    'member_id'=>$this->uid,
                    'goods_id'=>$post['goods_id'],
                    'add_integral'=>$post['integral'],
                    'creattime'=>time()
                ]);

                db('member_integrallog')->insert([
                    'member_id'=>$this->uid,
                    'describe'=>'参与评论',
                    'integral'=>$post['integral'],
                    'create_time'=>time(),
                ]);
                $member_integral= db('member')->where('member_id',$this->uid)->field('member_integral')->find();
                $where = (int)$member_integral['member_integral']+(int)$integral;
                db('member')->where('member_id',$this->uid)->update([
                    'updatetime'=>time(),
                    'member_integral'=>$where,
                ]);

                db('order')->where('order_id',$post['order_id'])->update([
                    'order_status'=>4
                ]);

                // 提交事务
                Db::commit();
                $shu=[
                    'code'=>0,
                    'msg'=>'评论成功',
                ];
                return json_encode($shu);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->success('评论失败',$e->getMessage(),1);
            }
        }
    }


    //退款按钮
    public function refund(){
        header('Access-Control-Allow-Origin:*');
        $order_id=input('order_id');
        if ($order_id){
            $da=  db('order')->where('order_id',$order_id)->update(
                [
                    'refund_status'=>1,
                    'updatetime'=>time(),
                ]
            );

            if ($da==true){
                return $this->success('申请成功等待后台处理','','0');
            }else{
                return $this->error('参数错误请稍后再试','','101');
            }
        }
    }



    //收藏
    public function collection(){
        $collection = model('Collection')
            ->where('member_id',$this->uid)
            ->order('creattime desc')
            ->select();
        $data=[];
        $img1='';

        $discoun_per=db('member_type')->where('member_type_id',  $this->member_type_id)->field('discoun_per')->find();
        foreach ($collection as $k=>$v){
            if ($v['collection_types']==2){
                $poi=  db('poi')->where('id',$v['goods_id'])
                    ->field('id,name,eng_name,thumb,score')
                    ->select();
                foreach ($poi as $l=>$s){
                    $img1= !empty($s['thumb'])?explode(',',$s['thumb']):'';
                    if ($img1!=''){
                        $img1 = $img1['1'];
                    }
                    $s['thumb']=$img1;
                    $data[]=[
                        'poi_id'=>$s['id'],
                        'name'=>$s['name'],
                        'eng_name'=>$s['eng_name'],
                        'thumb'=>$s['thumb'],
                        'score'=>$s['score']
                    ];
                }
                $collection['poi']=$data;
            }else if($v['collection_types']==1){
                $goods=  db('goods')->where('goods_id',$v['goods_id'])->where('show',1)
                    ->field('goods_id,goods_name,goods_englishname,goods_image,show,price')
                    ->select();
                $price='';
                foreach ($goods as $l=>$s){
                    $specs1=model('Specs')->alias('s')
                        ->where('s.goods_id',$s['goods_id'])
                        ->where('s.specs_status','1')
                        ->join('Person p','s.specs_id=p.specs_id')
                        ->where('p.person_status','1')
                        ->field('p.person_price')
                        ->select();

                    if (!empty($specs1)){
                        foreach ($specs1 as $k=>$v){
                            $price[]=$v['person_price'];
                        }

                        $max1= max($price);
                        $min1= min($price);
                        if ($max1==$min1){
                            $s['qujian1']=ceil(($min1*$discoun_per['discoun_per']));
                        }else{
                            $s['qujian1']=  ceil(($min1*$discoun_per['discoun_per'])).'~'.ceil(($max1*$discoun_per['discoun_per']));
                        }
                    }
                    $img= !empty($s['goods_image'])?explode(',',$s['goods_image']):'';
                    if(!empty($img['1'])){
                        $s['goods_image'] = $img['1'];
                    }
                    if($s['show']==2){
                        $exchange= db('exchange')->find();//汇率
                        $s['qujian1']=ceil($s['price']*$exchange['exchange_rate']);
                        $s['qujian1']=ceil($s['qujian1']*$discoun_per['discoun_per']);
                    }
                    $collection['goods'][]=$s;
                }
            }
        }
        $this->success('',$collection,0);
    }


    /**
     * 我的优惠卷
     */
    public function coupon(){
        $d= db('coupon')
            ->alias('a')
            ->join('coupondetails d','a.coupon_id=d.coupon_id')
            ->where('d.member_id',$this->uid)
            ->field('a.*,d.id,d.starttime as lingqushijian,d.usestatus')
            ->select();

        $data=[];
        $shu=[];

        if (!empty($d)) {
            foreach ($d as $v) {
                if ($v['usestatus'] == 0) {
                    if ($v['end_usetime'] < time()) {
                        $data = [];
                    } else {
                        $v['full_reduction'] = '';
                        if ($v['coupon_types'] == 2) {
                            $v['full_reduction'] = $v['coupon_discount'];
                            $v['coupon_discount'] = '';
                        }
                        $data[] = [
                            "coupon_id" => $v['id'],
                            "discount" => $v['coupon_discount'],//折扣
                            "full_reduction" => $v['full_reduction'],//满减
                            "validityperiod" => date('Y-m-d', $v['etart_usetime']) . '-' . date('Y-m-d', $v['end_usetime']),//使用条件
                            "coupon_usecondition" => $v['coupon_usecondition'],//使用条件
                            "usestatus" => $v['usestatus'],//
                        ];
                    }
                }
            }
        }
        $this->success('',$data,0);
    }


    public function application(){
        $is_apply= input('is_apply');
        $data= db('member')->where('member_id',$this->uid)->update([
            'is_apply'=>$is_apply,
            'updatetime'=>time()
        ]);
        if ($data){
            $this->success('申请成功','','0');
        }else{
            $this->error('申请失败','','0');
        }
    }


    public function isapply(){
        $data= db('member')->where('member_id',$this->uid)->field('is_apply')->find();
        $discoun_per=db('member_type')->where('member_type_id',  $this->member_type_id)->where('type_status',1)->field('member_type_id,type_name,description')->find();
        $data['member_type']=$discoun_per;
        if ($discoun_per['member_type_id']=='1'&& $data['is_apply']!=1){
            db('member')->where('member_id',$this->uid)
                ->update(['is_apply'=>0]);
            $data['is_apply']=0;
        }
        if ($data==true){
            $this->success('',$data,'0');
        }else{
            $this->error('请求失败','','0');
        }
    }

}